<?php
/**
 * Created by PhpStorm
 *
 * @author  : yiyu
 * @time    : 2018/3/21 11:24
 * @desc    : 腾讯云对象储存
 * @fileName: COS.php
 */

namespace app\core\storage;

use Qcloud\Cos\Client;

class COS
{

    private static $COSClient = null;

    /**
     * Desc: 获取COS对象
     * Date: 2019/11/4 20:31
     * Author: yiyu
     * @return Client|null
     */
    public static function getCOSClient()
    {
        if (self::$COSClient === null) {
            self::$COSClient = new Client(config('cos'));
        }
        return self::$COSClient;
    }

    /**
     * Desc: 上传对象到指定的存储桶中（PUT Object）
     * Date: 2019/11/4 19:07
     * Author: yiyu
     * @param string $file_name 文件名
     * @param string $file_local_path 本地路径
     * @param string $key 功能归属
     * @return array
     */
    public static function putObject($file_name, $file_local_path, $key = '')
    {
        $key = empty($key) ? 'public/' . date('Ymd') : $key;
        try {
            self::getCOSClient()->putObject([
                'Bucket' => config('cos_bucket'),
                'Key' => $key . '/' . $file_name,
                'Body' => fopen($file_local_path, 'rb')
            ]);

            return [
                'cos_url' => config('cos_host') . '/' . $key . '/' . $file_name,
                'cos_path' => $key . '/' . $file_name
            ];
        } catch (\Exception $e) {
            return [
                'line' => $e->getLine(),
                'msg' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ];
        }
    }


    /**
     * Desc: 上传对象到指定的存储桶中（PUT Object）
     * Date: 2019/11/4 20:26
     * Author: yiyu
     * @param string $fullFileName 全路径文件名
     * @param string $project
     * @return array
     */
    public static function simplePutObject($fullFileName, $project = '')
    {
        $pathInfo = pathinfo($fullFileName);
        return self::putObject($pathInfo['basename'], $pathInfo['dirname'], $project);
    }

    /**
     * Desc: 上传对象到指定的存储桶中（PUT Object）
     * Date: 2019/11/4 19:07
     * Author: yiyu
     * @param string $fileName 文件名
     * @param string $path 本地路径
     * @param string $key 功能归属
     * @return array
     */
    public static function upload($fileName, $path, $key = '')
    {
        $key = empty($key) ? 'public/' . date('Ymd') : $key;

        try {
            self::getCOSClient()->upload(config('cos_bucket'), $key, fopen($path, 'rb'));

            return [
                'cos_url' => config('cos_host') . '/' . $key . '/' . $fileName,
                'cos_path' => $key . '/' . $fileName,
            ];
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * Desc: 查询 Object 的 Meta 信息（HEAD Object）
     * Date: 2019/11/4 19:47
     * Author: yiyu
     * @param $key
     * @return mixed
     */
    public static function headObject($key)
    {
        return self::getCOSClient()->headObject([
            'Bucket' => config('cos_bucket'),
            'Key' => $key,
        ]);
    }

    /**
     * Desc: 下载对象到本地（GET Object）
     * Date: 2019/11/4 19:51
     * Author: yiyu
     * @param $key
     * @return bool
     */
    public static function getObject($key)
    {
        if (strpos($key, config('domain') . DS) !== false) {
            $tmp = explode(config('domain') . DS, $key);
            $key = $tmp[1];
        } else {
            $key = trim($key, DS);
        }

        try {
            $result = self::getCOSClient()->getObject([
                'Bucket' => config('cos_bucket'),
                'Key' => $key,
            ]);
            return $result;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Desc: 在存储桶中删除指定 Object （文件/对象）
     * Date: 2019/11/4 19:53
     * Author: yiyu
     * @param $key
     * @return mixed
     */
    public static function deleteObject($key)
    {
        return self::getCOSClient()->deleteObject([
            'Bucket' => config('cos_bucket'),
            'Key' => $key,
        ]);
    }

    /**
     * Desc: 查询指定账号下所有存储桶列表（GET Service）
     * Date: 2019/11/4 17:05
     * Author: yiyu
     * @return mixed
     */
    public static function getBucketList()
    {
        try {
            return self::getCOSClient()->listBuckets();
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * Desc: 在指定账号下创建一个存储桶（PUT Bucket）
     * Date: 2019/11/4 17:09
     * Author: yiyu
     * @param $bucket
     * @return bool
     */
    public static function createBucket($bucket)
    {
        try {
            return self::getCOSClient()->createBucket(['Bucket' => $bucket]);
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Desc: 删除指定账号下的空存储桶
     * Date: 2019/11/4 17:22
     * Author: yiyu
     * @param $bucket
     * @return bool
     */
    public static function deleteBucket($bucket)
    {
        try {
            return self::getCOSClient()->deleteBucket(['Bucket' => $bucket]);
        } catch (\Exception $e) {
            return false;
        }
    }
}